package ps.client.plugin.eq2.log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;


public class LogReader implements Runnable {
	
	public static final String LOG_FILE_CHAR_ENCODING = "UTF8";
	
	public static final String REGEX_LOG_START = ".*Logging to '.*' is now \\*ON\\*";
	
	public static final Pattern PATTERN_TIME_STAMP = Pattern.compile("\\([0-9]{10}\\).*");
	
	BufferedReader reader;
	
	LogFileFinder logFileFinder;
	LogParser parser;
	
	File currentLogFile = null;
	
	boolean running = true;
	
	int lineCount = 0;
	long lastRead = 0;
	
	long startTime = Long.MAX_VALUE;
	
//	Object readingMutex = new Object();

	public LogReader(LogFileFinder logFileFinder, LogParser parser) {
		this.logFileFinder = logFileFinder;
		this.parser = parser;
	}
	
	public void run() {
		try {
			while (running) {
			    if (currentLogFile != logFileFinder.getCurrentLogFile()) {
			        setStartTime(Long.MAX_VALUE);
			        setLogFile(logFileFinder.getCurrentLogFile());
			    }
//				if (logFileFinder.isLogFileChanged()) {
//					setLogFile(logFileFinder.getCurrentLogFile());
//				}
				while (reader != null && reader.ready()) {
					String line = new String(reader.readLine().getBytes(), LOG_FILE_CHAR_ENCODING);
	                parser.parse(line);
	                lineCount++;
	                lastRead = System.currentTimeMillis();
		            Thread.yield();
				}
				Thread.sleep(100);
			}
		} catch (Exception ex) {
		    if (running) {
		        ex.printStackTrace();
		    }
		}
	}
	
	public void parseFileSynchron() throws Exception {
	    setLogFile(logFileFinder.getCurrentLogFile());
        while (reader != null && reader.ready()) {
            String line = new String(reader.readLine().getBytes(), LOG_FILE_CHAR_ENCODING);
            parser.parse(line);
            lineCount++;
        }
	}
	
	public void stop() throws IOException {
		running = false;
        if (reader != null) {
            reader.close();
        }
	}
	
	public void setStartTime(long startTime) {
	    this.startTime = startTime;
	}
	
	void setLogFile(File logFile) throws IOException {
	    currentLogFile = logFile;
	    
		if (reader != null) {
			reader.close();
		}
		reader = new BufferedReader(new FileReader(logFile));
		
		if (startTime > System.currentTimeMillis()) {
		    while (reader.ready()) {
		        reader.readLine();
		    }
		} else {
		    // find start of parsing
	        while (reader.ready()) {
	            String line = reader.readLine();
	            if (PATTERN_TIME_STAMP.matcher(line).matches()) {
	                long lineTime = Long.parseLong(line.substring(1, 11)) * 1000;
	                if (lineTime > startTime) {
//	                    System.out.println("starte mit line: " + line);
	                    try {
	                        reader.reset();
	                    } catch (Exception ex) {
	                    }
	                    break;
	                } else {
	                    reader.mark(512);
	                }
	            }
	        }
		}
		
//		lastRead = System.currentTimeMillis();
		
		parser.parseLogFilePath(logFile.getAbsolutePath());
	}
	
	public long getLastRead() {
	    return lastRead;
	}
	
	public static void main(String[] args) throws Exception {
//		Runnable logParser = new LogReader(
//				"E:\\Games\\EverQuest II\\LP_REGION_EN_US\\logs\\Everfrost\\eq2log_heile.txt", new LogParser());
//		Thread logThread = new Thread(logParser, "LogParser");
//		logThread.start();
		
//		System.out.println("Logging to 'logs/Everfrost/eq2log_Lumpen.txt' is now *ON*".matches(REGEX_LOG_START));
//		System.out.println(System.currentTimeMillis());
		
		System.out.println(new String("You say, ü".getBytes(), "UTF8"));
	}
}
